package org.wmq.javafxmapcollectioncs.mapper.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.wmq.javafxmapcollectioncs.mapper.CommentMapper;
import org.wmq.javafxmapcollectioncs.model.Entity.Comment;
import org.wmq.javafxmapcollectioncs.model.Entity.Result;

import java.io.IOException;

public class CommentMapperImplByHttpAndMysql implements CommentMapper {
    @Override
    public String selectById(Long id) {
        String url = "http://localhost:8080/comment/" + id;
        String resultJson = HttpUtil.get(url);
        Result<String> result = JSON.parseObject(resultJson, Result.class);
        return result.getData();
    }

    @Override
    public void insert(Long id, String content) throws IOException {
        String url = "http://localhost:8080/comment";
        Comment comment = new Comment(content);
        comment.setId(id);
        HttpUtil.post(url,JSON.toJSONString(comment));
    }

    @Override
    public void update(Long id, String content) {
        String url = "http://localhost:8080/comment";
        Comment comment = new Comment(content);
        comment.setId(id);
        HttpUtil.createRequest(Method.PUT,url).
                body(JSON.toJSONString(comment))
                .execute();
    }

    @Override
    public void deleteById(Long id) {
        String url = "http://localhost:8080/comment/" + id;
        HttpDelete httpDelete = new HttpDelete(url);
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            try (CloseableHttpResponse response = httpclient.execute(httpDelete)) {
                System.out.println(response.getVersion()); // HTTP/1.1
                System.out.println(response.getCode()); // 200
                System.out.println(response.getReasonPhrase()); // OK
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}